<template>
	<view style="background-color: #F1F1F1;">
		<block>
			<uni-nav-bar @clickLeft="goBack" status-bar="true" shadow="true" left-icon="back" left-text="返回" title="录入案例"></uni-nav-bar>
		</block>
		<view class="out-input" v-if="rootTopicId.length==0">
			<label class="lable-radio" style="font-weight: bold; font-size: large;">初诊
				<radio v-model="postData.isFirst" class="radio" value="r1" @tap="changChecked" :checked="postData.isFirst" color="#007AFF"
				 style="transform:scale(0.8)" /></label>
		</view>
		<view class="uni-form-item">
			<view class="title">
				就诊时间
			</view>
			<picker style="margin-left: 32%;" mode="date" :value="postData.consultTime" :start="startDate" :end="endDate" @change="bindDateChange">
				<view class="uni-input">{{postData.consultTime}}</view>
			</picker>
		</view>
		<!-- <view class="under-line"></view> -->

		<view class="uni-form-item" v-if="rootTopicId.length==0">
			<view class="title">城市</view>
			<picker style="margin-left: 32%;" mode="region" @change="onChange">
				<view class="uni-input">{{postData.location}}</view>
			</picker>
		</view>

		<!-- <view class="under-line"></view> -->
		<view class="uni-form-item " v-if="rootTopicId.length==0">
			<view class="title">大夫</view>
			<input style="margin-left: 5%;" v-model="postData.doctor" @focus="getFocus(0)" class="uni-input " v-bind:class="{ 'input-error': hasError[0] }"
			 placeholder="请输入大夫姓名" />
		</view>


		<!-- <view class="under-line"></view> -->
		<view class="uni-form-item " v-if="rootTopicId.length==0">
			<view class="title">诊所医院</view>
			<input v-model="postData.clinic" @focus="getFocus(1)" v-bind:class="{ 'input-error': hasError[1] }" class="uni-input"
			 placeholder="请输入诊所或医院" />
		</view>
		<!-- <view class="under-line" style="height: 0.5px;"></view> -->
		<view class="uni-form-item "  v-if="rootTopicId.length==0">
			<view class="title">求诊疾病</view>
			<input v-model="postData.diseseName" @focus="getFocus(2)" v-bind:class="{ 'input-error': hasError[2] }" class="uni-input"
			 placeholder="请输入求诊疾病" />
		</view>
		<!-- <view class="under-line"></view> -->
		<view class="uni-form-item " >
			<view class="title">诊前情况</view>
			<textarea  v-model="postData.beforeCase" class="textarea" placeholder="请输入诊前情况(可包括患者性别,年龄)" @blur="bindTextAreaBlur" auto-height />
		</view>
		<!-- <view class="under-line" ></view> -->
		<view class="uni-form-item "   >
			<view class="title">诊后情况</view>
			<textarea v-model="postData.afterCase" class="textarea"  placeholder="请输入诊后情况" @blur="bindTextAreaBlur" auto-height />
		</view>
		<!-- <view class="under-line"></view> -->
		<view class="comment-list " style=" float: left;">
			<view class="titleDegress" >好评度</view>
			<radio-group @change="radioChange"  class="coomment-list-cell">
				<label style="font-size: large;"  v-for="(item, index) in degressItems" :key="item.value">
					<view >
						<view style="float: left; display: inline-block; font-size: large;" >{{item}}</view>
						<radio :value="item" :checked="index === current" color="#007AFF" style="transform:scale(0.8);" />
					</view>	
				</label>
			</radio-group>
		</view>
		<view class="uni-list list-pd">
			<view class="uni-list-cell cell-pd">
				<view class="uni-uploader">
					<view class="uni-uploader-head">
						<view class="uni-uploader-title" style="font-size: large;" >就医凭证</view>
						<view class="uni-uploader-info">{{postData.casePics.length}}/9</view>
					</view>
					<view class="uni-uploader-body "  v-bind:class="{ 'input-error': hasError[3] }">
						<view class="uni-uploader__files">
							<block v-for="(image,index) in postData.casePics" :key="index">
								<view class="uni-uploader__file" style="position: relative; " >
									<view class="delete-image icon iconfont icon-delete"  :data-src="image" @tap="deleteIt"></view>
									<image class="uni-uploader__img"  :src="image" :data-src="image" @tap="previewImage"></image>
								
								</view>
								
							</block>
							<view class="uni-uploader__input-box">
								<view class="uni-uploader__input"  @tap="chooseImage"></view>
							</view>
						</view>
					</view>
				</view>
			</view>
		</view>
		<view class="uni-padding-wrap uni-common-mt button-save"  >
		<button v-if="rootTopicId.length==0"  style="flex-grow: 1;" @tap="goSave" >保存</button>
		<button type="primary"  style="color: #FFFFFF; flex-grow: 1;" @tap="goPostData">发布</button>
		</view>
	</view>

</template>

<script>
	import uniNavBar from "@/components/uni-nav-bar/uni-nav-bar.vue"
	import permision from "@/common/permission.js"
	import config from "@/common/config.js"
	var sourceType = [
		['camera'],
		['album'],
		['camera', 'album']
	]
	var sizeType = [
		['compressed'],
		['original'],
		['compressed', 'original']
	]
	function getDate(type) {
		const date = new Date();
	
		let year = date.getFullYear();
		let month = date.getMonth() + 1;
		let day = date.getDate();
	
		if (type === 'start') {
			year = year - 60;
		} else if (type === 'end') {
			year = year + 2;
		}
		month = month > 9 ? month : '0' + month;;
		day = day > 9 ? day : '0' + day;
	
		return `${year}-${month}-${day}`;
	}
	export default {
		components: {
			uniNavBar
		},
		data() {
			return {
				testIma:"http://127.0.0.1:3000/uploads/upload_bf5f9a8fd2953f4836cc6c61b0f274a1.png",
				degressItems:['满意','一般','差'],
				current:1,
				sourceTypeIndex: 2,
				sourceType: ['拍照', '相册', '拍照或相册'],
				sizeTypeIndex: 2,
				sizeType: ['压缩', '原图', '压缩或原图'],
				countIndex: 8,
				count: [1, 2, 3, 4, 5, 6, 7, 8, 9],
				//表单属性
				postData:{
					isFirst: false,
					consultTime: getDate({
								format: true
								}),
					doctor:"",
					location:"请选择就诊地区",
					clinic:"",
					diseseName:"",
					beforeCase:"",
					afterCase:"",
					degress:"1",
					casePics: []// 病例图片
				},
				hasError:[false,false,false,false],
				token:'',
				date: getDate({
					format: true
				}),
				startDate:getDate('start'),
				endDate:getDate('end'),
				time: '12:01',
				rootTopicId:''
			}
			
		},
		methods: {
			onChange(event){
				var prince = event.detail.value[0]==event.detail.value[1]?event.detail.value[0]:event.detail.value[0]+'-'+event.detail.value[1];
				var location =prince +'-'+event.detail.value[2];
				this.postData.location = location;
			},
			handleDoctorChange(event){
				 this.postData.doctor= event.mp.detail;
			},
			onLoad(option) {
				this.token = uni.getStorageSync(config.token);
				if(option.id){
					this.rootTopicId = option.id;
					this.postData.doctor = option.doctor;
					this.postData.diseseName = option.diseseName;
					this.postData.clinic = option.clinic;
					this.postData.location = option.location;
				}
			},
			goBack() {
				
				uni.removeStorage({
				    key: config.PostDataKey,
				    success: function (res) {
				        console.log('success');
				    }
				});
				uni.navigateBack({

				})

			},
			changChecked() {
				if (this.postData.isFirst) {
					this.postData.isFirst = false;
				} else {
					this.postData.isFirst = true;
				}
			},
			radioChange(e){
				console.log(e.target.value);
				this.postData.degress =this.degressItems.indexOf(e.target.value).toString();
				
			},
			//拍照
			chooseImage: async function() {
				this.hasError.splice(3,1,false);
				// #ifdef APP-PLUS
				// TODO 选择相机或相册时 需要弹出actionsheet，目前无法获得是相机还是相册，在失败回调中处理
				if (this.sourceTypeIndex !== 2) {
					let status = await this.checkPermission();
					if (status !== 1) {
						return;
					}
				}
				// #endif
			
				if (this.postData.casePics.length === 6) {
					let isContinue = await this.isFullImg();
					console.log("是否继续?", isContinue);
					if (!isContinue) {
						return;
					}
				}
				uni.chooseImage({
					sourceType: sourceType[this.sourceTypeIndex],
					sizeType: sizeType[this.sizeTypeIndex],
					count: this.postData.casePics.length + this.count[this.countIndex] > 9 ? 9 - this.postData.casePics.length : this.count[this.countIndex],
					success: (chooseImageRes) => {
						var b = config.baseUrl+'/upload';
						const tempFilePaths = chooseImageRes.tempFilePaths;
						for(var i=0; i< tempFilePaths.length;i++){
							uni.uploadFile({
								url:b,
								filePath: tempFilePaths[i],
								name: 'file',
								success: (uploadFileRes) => {
									console.log(uploadFileRes);
									if(uploadFileRes.statusCode==200){
										var ob = JSON.parse(uploadFileRes.data);
										 this.postData.casePics.push(ob.url);
									}else{
										uni.showToast({
											duration:2000,
											title:'图片上传失败'
										})
									}
								  
								}
							});
						}
						
					},
					fail: (err) => {
						// #ifdef APP-PLUS
						if (err['code'] && err.code !== 0 && this.sourceTypeIndex === 2) {
							this.checkPermission(err.code);
						}
						// #endif
						// #ifdef MP
						uni.getSetting({
							success: (res) => {
								let authStatus = false;
								switch (this.sourceTypeIndex) {
									case 0:
										authStatus = res.authSetting['scope.camera'];
										break;
									case 1:
										authStatus = res.authSetting['scope.album'];
										break;
									case 2:
										authStatus = res.authSetting['scope.album'] && res.authSetting['scope.camera'];
										break;
									default:
										break;
								}
								if (!authStatus) {
									uni.showModal({
										title: '授权失败',
										content: 'Hello uni-app需要从您的相机或相册获取图片，请在设置界面打开相关权限',
										success: (res) => {
											if (res.confirm) {
												uni.openSetting()
											}
										}
									})
								}
							}
						})
						// #endif
					}
				})
			},
			previewImage: function(e) {
				var current = e.target.dataset.src
				uni.previewImage({
					current: current,
					urls: this.postData.casePics
				})
			},
			deleteIt: function(e){
				var current = e.target.dataset.src;
				console.log(current);
				var index = this.postData.casePics.indexOf(current);
				this.postData.casePics.splice(index,1);
				
			},
			async checkPermission(code) {
				let type = code ? code - 1 : this.sourceTypeIndex;
				let status = permision.isIOS ? await permision.requestIOS(sourceType[type][0]) :
					await permision.requestAndroid(type === 0 ? 'android.permission.CAMERA' :
						'android.permission.READ_EXTERNAL_STORAGE');
			
				if (status === null || status === 1) {
					status = 1;
				} else {
					uni.showModal({
						content: "没有开启权限",
						confirmText: "设置",
						success: function(res) {
							if (res.confirm) {
								permision.gotoAppSetting();
							}
						}
					})
				}
			
				return status;
			},
			bindTextAreaBlur(){
				
			},
			goPostData(){
				if(this.postData.doctor.trim().length===0){
					console.log('doctor is empty')
					this.hasError.splice(0,1,true);
					return;
				}
				if(this.postData.clinic.trim().length===0){
					this.hasError.splice(1,1,true);
					return;
				}
				if(this.postData.diseseName.trim().length===0){
					this.hasError.splice(2,1,true);
					return;
				}
				if(this.postData.casePics.length===0){
					this.hasError.splice(3,1,true);
					return;
				}
				var b = config.baseUrl+'/topics';
				//http://127.0.0.1:3000/topics/5e478ef4a05e82fca1f64955
				if(this.rootTopicId.length>0){
					b=b+'/'+this.rootTopicId;
				}
				uni.request({
					method:'POST',
				    url: b, //仅为示例，并非真实接口地址。
				    data: this.postData,
				    header: {
				        'content-type': 'application/json' ,//自定义请求头信息
						'Authorization':'Bearer '+this.token//通过登录接口，生成新的token
				    },
				    success: (res) => {
						var statusCode = res.statusCode;
						if(200==statusCode){
							uni.removeStorage({
							    key: config.PostDataKey,
							    success: function (res1) {
							    }
							}); 
							uni.showToast({
								title: "发布成功",
								duration: 3000,
								complete: () => {
									uni.navigateBack();
								}
							});
						}else if(401==statusCode){
							//token 相关到错误
							//1,session过期或不存在：直接手机号和密码登录（后期短信验证码），返回token
							//2，session 有效：session登录(一键登录)，返回token
							//跳转后显示微信登录按钮。
							this.checkSession();
							
						}else{
							uni.showToast({
								title: "发布失败else",
								duration: 2000,
							});
						}
				    },
					fail:(res)=>{
						uni.showToast({
							title: "发布失败fail"
						});
					},
					complete: () => {
						
					}
				});
			},
			goSave(){
				console.log(this.postData);
				uni.setStorage({
				    key: config.PostDataKey,
				    data: this.postData,
				    success: function () {
				        uni.navigateBack();
				        uni.showToast({
				        	title: "保存成功",
				        	duration: 2000,
				        });
				    }
				});
			},
			getFocus(e){
				
				this.hasError.splice(e,1,false);
			},
			bindDateChange: function(e) {
				this.postData.consultTime = e.target.value
			},
			checkSession(){
				uni.checkSession({
					success: (e) => {
						var weixinsession = uni.getStorageSync(config.sessionkey);
						if (weixinsession.length > 0) {
							uni.navigateTo({
								url: '../loginnew/loginnew'
							})
						} else {
							uni.navigateTo({
								url: '../authorityRequst/authorityRequst'
							})
						}
				
					},
					fail: () => {
						console.log("yijinggoqdi")
						uni.navigateTo({
							url: '../authorityRequst/authorityRequst'
						})
					}
				});
			}
			
		}
	}
</script>

<style>
	.out-input {
		padding-top: 30upx;
		padding-left: 70upx;
		/* padding: 10upx; */
	}

	.radio {
		padding-left: 20upx;
	}

	.picker {
		display: flex;
		flex-flow: row;
	}

	.uni-list-cell {
		/* height: 100upx; */
		padding-left: 30upx;
	}
	.uni-form-item{
		display: block;
		/* height: 100upx; */
		padding-left: 30upx;
		padding-right: 30upx;
		width: auto;
		flex-direction: column;
	}

	.uni-list-cell::after {
		right: 30upx;
		transform: scaleY(1);
		background-color: #FFFFFF;

	}
	.under-line {
		
		width: auto;
		height: 0.5upx;
		background-color: #EEEEEE;
	}
	.title{
		width: 25%;
		float: left;
		font-size: large;
		font-weight: bold;
	}
	.oldtitle{
		padding-left: 20upx;
		font-size: large;
		font-weight: bold;
	}
	.textarea{
		padding-top: 10upx;
		padding-left: 30upx;
		padding-right: 30upx;
		margin-right: 30upx;
		font-size: 30upx;
	}
	.lable-radio{
		padding-top: 10upx;
		padding-right: 30upx;
	}
	.comment-list{
		padding-left: 40upx;
		display: flex;
		flex-direction: row;
	}
	.coomment-list-cell{
		display: flex;
		flex-direction: row;
		padding-top: 5upx;
	}
	.delete-image{
		font-size: 30upx;
		color: #FF3333;
		font-weight: bold;
		position: absolute;
		top: 0px;
		right: 0px;
	}
	.button-save{
		display: flex;
		
		flex-direction: row;
		
	}
	.uni-uploader-title{
		font-weight: bold;
		padding-top: 20upx;
	}	
	.input-error{
		border:2upx solid #FF3333;
	}
	input{
		font-size: large;
	}
	.textarea{
		font-size: large;
		display: block;
		margin-left: 32%;
		width: 60%;
		padding: 15rpx 25rpx;
		background-color: #FFFFFF;
	}
	.uni-list-cell-left{
		font-size: large;
		font-weight: bold;
	}
	.uni-input{
		font-size: large;
	}
	.titleDegress{
		padding-left: 20upx;padding-right: 20upx; width: 30%;
		float: left;
		font-size: large;
		font-weight: bold;
	}
</style>
